package view;

import android.content.Context;
import android.text.Layout;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class AutoFitTextView extends TextView {
    public static final String TAG = "AutoFitTextView";

    private float mDesiredTextSize;



    public AutoFitTextView(Context context) {
        super(context);

        init();
    }

    public AutoFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public AutoFitTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }



    private void init() {
        this.mDesiredTextSize = getTextSize();

        setSingleLine();
        setEllipsize(TruncateAt.END);
    }



    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);

        if (mDesiredTextSize > 0 && text != null && text.length() > 0) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, mDesiredTextSize);
            final Layout layout = getLayout();
            if (layout != null) {
                final int lineCount = layout.getLineCount();
                if (lineCount > 0) {
                    final int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
                    if (ellipsisCount > 0) {
                        boolean resize = true;
                        while (resize) {
                            float textWidth = getPaint().measureText(getText().toString()); 
                            int viewWidth = getWidth();
                            if (textWidth <= viewWidth) {
                                resize = false;
                            } else {
                                final float textSize = getTextSize();
                                setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));
                            }
                        }
                    }
                }
            }
        }
    }
}